import type { FileItem } from '@/hooks/useUpload'
import type { Props as useUploadProps } from '@/hooks/useUpload'
import type { ImageUploaderProps, ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import { ImageUploader, Toast } from 'antd-mobile'
import useUpload from '@/hooks/useUpload'

interface Props extends useUploadProps {
    fileList?: FileItem[]
}

/** 上传图片 */
const UploadImage: React.FC<Props> = props => {
    const { fileList, setFileList, beforeUpload, defaultUpload } = useUpload({ ...props })

    /** 上传图片之前 */
    const onBeforeUpload: ImageUploaderProps['beforeUpload'] = (file, files) => {
        /** 验证全部文件 */
        const approveAll = files.every(_file => {
            const { approve, msg } = beforeUpload(_file)

            if (approve === false) Toast.show({ icon: 'fail', content: msg })

            return approve === true
        })

        if (approveAll) {
            return file
        } else {
            return null
        }
    }

    /** 上传图片 */
    const onUpload = async (file: File): Promise<ImageUploadItem> => {
        const res = defaultUpload({ file })

        res.catch(() => Toast.show({ icon: 'fail', content: '上传失败' }))

        const data = await res

        return {
            key: data.id,
            url: data.url,
            extra: {
                name: file.name,
            },
            thumbnailUrl: data.url,
        }
    }

    return (
        <ImageUploader
            maxCount={props.maxCount}
            value={fileList}
            onChange={items => {
                props.onChange?.(items)
                setFileList(items)
            }}
            beforeUpload={onBeforeUpload}
            upload={onUpload}
        />
    )
}

export default UploadImage
